import markdown
from django.shortcuts import render, get_object_or_404

# Create your views here.

from django.http import HttpResponse

from blog.models import Post, Category


def index(request):
    posts = Post.objects.all()
    print(posts)

    return render(request, 'blog/index.html', context={
        'posts': posts
    })


def detail(request, id):
    post = get_object_or_404(Post, id=id)
    # 记得在顶部引入 markdown 模块
    # extensions，它是对 Markdown 语法的拓展，这里我们使用了三个拓展
    # 1). extra 本身包含很多拓展，
    # 2). codehilite 是语法高亮拓展
    # 3). toc 则允许我们自动生成目录
    post.body = markdown.markdown(post.body,
                                  extensions=[
                                      'markdown.extensions.extra',
                                      'markdown.extensions.codehilite',
                                      'markdown.extensions.toc',
                                  ])
    # 阅读量 +1
    post.increase_views()
    return render(request, 'blog/detail.html', context={'post': post})


def category(request, pk):
    # 记得在开始部分导入 Category 类
    cate = get_object_or_404(Category, id=id)
    post_list = Post.objects.filter(category=cate).order_by('-created_time')
    return render(request, 'blog/index.html', context={'post_list': post_list})


def archives(request, year, month):
    post_list = Post.objects.filter(created_time__year=year,
                                    created_time__month=month
                                    ).order_by('-created_time')
    return render(request, 'blog/index.html', context={'post_list': post_list})
